using namespace std;
#include<unistd.h>
#include<iostream>
#include<sys/types.h>
#include<sys/wait.h>
void ChildWrite(int wfd)
{
    int cnt=0;
    while(true)
    {
        sleep(1);
        write(wfd,&cnt,sizeof(cnt));
        cnt++;
        // printf("child:%d\n",cnt++);
        if(cnt==10)
        {
            break;
        }
    }
}
void FatherRead(int rfd)
{
    // char buffer[1024];
    int num;
    while(true)
    {
        // buffer[0] = 0;
        // ssize_t n =read(rfd,buffer,sizeof(buffer)-1);
        ssize_t n =read(rfd,&num,sizeof(num));
        if(n>0)
        {
            // sleep(2);
            // buffer[n] = 0;
            std::cout<<"child say:"<<num<<std::endl;
        }
        else if(n == 0)
        {
            std::cout<<"n:"<<n<<std::endl;
            std::cout<<"child 退出,我也退出";
            break;
        }
        else
        {
            break;
        }
    }
}
int main()
{
    int fds[2]={0};
    int n = pipe(fds);
    if(n<0)
    {
        std::cerr<<"pipe error"<<std::endl;
        return 1;        
    }
    std::cout<<"fds[0]: "<<fds[0]<<std::endl;
    std::cout<<"fds[1]: "<<fds[1]<<std::endl;
    pid_t id = fork();
    if(id == 0)
    {
        close(fds[0]);
        ChildWrite(fds[1]);
        close(fds[1]);
        exit(0);
    }
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);
    sleep(2);
    int status = 0;
    int ret = waitpid(id,&status,0);
    if(ret > 0)
    {
        printf("exit code: %d,exit signal:%d\n",(status>>8)&0xFF,status&0x7F);
        sleep(1);
    }
    return 0;
}